<!DOCTYPE html>
<html lang="zh-CN">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.ico">
  <link rel="icon" type="image/png" href="/img/favorite.ico">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="小九的日常笔记">
  <meta name="author" content="小九">
  <meta name="keywords" content="笔记，博客，前端，html，css，javascript，面试题，前端面试题">
  <title>event loop事件循环机制 - 小九的书柜</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->

  
<link rel="stylesheet" href="/css/my.css">



<!-- 
<link rel="stylesheet" href="/css/message.css">
 -->
<!-- 
<link rel="stylesheet" href="https://at.alicdn.com/t/font_1117508_wxidm5ry7od.css">
 -->

  <script  src="/js/utils.js" ></script>
<meta name="generator" content="Hexo 4.2.1"></head>



<body>
  
  <div id="background">
    <!--  -->
    <header style="height: 70vh;">
      <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
      href="/">&nbsp;<strong>jLongYan's blog</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
      data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false"
      aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/">
            <i class="iconfont icon-home-fill"></i>
            首页
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/archives/">
            <i class="iconfont icon-archive-fill"></i>
            归档
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/categories/">
            <i class="iconfont icon-category-fill"></i>
            分类
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/tags/">
            <i class="iconfont icon-tags-fill"></i>
            标签
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/links/">
            <i class="iconfont icon-link-fill"></i>
            友链
          </a>
        </li>
        
        
        
        
        
        
        

        <li class="nav-item 1 " </li>
          <a class="nav-link 1 " href="/about/">
            <i class="iconfont icon-user-fill"></i>
            关于
          </a>
        </li>
        
        
        
        <li class="nav-item" onclick="switchDarkMode()">
          <span id="dark"></span>
        </li>
        
      </ul>
    </div>
  </div>
</nav>
<style>
  .active {
    /* border-bottom: 1px solid #00FFFF; */
    color: #00FFFF !important;
  }
</style>

<script>
  var isNight = new Date().getHours() >= 22 || new Date().getHours() < 5; // 指定时间
  // 依次判断 系统暗黑模式 指定时间 缓存 dark
  if (matchMedia('(prefers-color-scheme: dark)').matches || isNight || localStorage.getItem('dark') === '1') {
    if (!(isNight && localStorage.getItem('noDark') === '1')) {
      document.body.classList.add('dark');
    }
  }
  //点击事件
  function switchDarkMode() {
    if ($('body').hasClass('dark')) {
      // checkWallaper()
      document.getElementById('dark').style.backgroundImage = 'url(/img/太阳.png)'
      document.body.classList.remove('dark');
      localStorage.setItem('noDark', '1');
      localStorage.setItem('dark', '0');
    } else {
      document.getElementById('dark').style.backgroundImage = 'url(/img/月亮.png)'
      document.body.classList.add('dark');
      localStorage.setItem('dark', '1');
      localStorage.setItem('noDark', '0');
      // checkWallaper()
    }
  }

</script>



      <!-- 如果需要采用配置文件的路径 在下面的div粘贴此段代码进去即可 目前采用的是 自定义的随机图片 -->
      <!-- style="background: url('/headImg/headImg.jpg') no-repeat center center;background-size: cover;" -->
      <div class="view intro-2" id="indexBackground" parallax=true
        style='background-size:cover'>
        <div class="full-bg-img">
          <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.1)">
            <div class="container text-center white-text fadeInUp">

              <span class="h2" id="subtitle">
                
              </span>

              <div id="yiyan" onclick="watchYiyan()">只有极其努力，才能看起来毫不费力。</div>

              


              
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2018-07-15 18:38">
      2018年7月15日 晚上
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.2k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      15
       分钟
    </span>
  

  
  
    
  
</div>
<!-- <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script> -->
              
            </div>

            
            <div class="scroll-down-bar">
              <i class="iconfont icon-arrowdown"></i>
            </div>
            
          </div>
        </div>
      </div>
    </header>
    <!--  -->



    <main>
      
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
              <p class="note note-info">
                
                  本文最后更新于：2020年8月5日 上午
                
              </p>
            
            <article class="markdown-body">
              <h3 id="从event-loop出发讨论Promise、setTimeout的执行顺序"><a href="#从event-loop出发讨论Promise、setTimeout的执行顺序" class="headerlink" title="从event loop出发讨论Promise、setTimeout的执行顺序"></a>从event loop出发讨论Promise、setTimeout的执行顺序</h3><hr>
<p>Event Loop 这个概念相信大家或多或少都了解过,所谓温故而知新，so，今天，我们就从event loop出发，看看在事件的执行过程中，他都经历了些什么。</p>
<h4 id="什么是event-loop"><a href="#什么是event-loop" class="headerlink" title="什么是event loop"></a>什么是event loop</h4><p>event loop是js的事件执行机制，我们一般简称为事件循环（之所以称作事件循环，是因为它经常被用于类似如下的方式来实现）</p>
<pre><code class="hljs javascript"><span class="hljs-keyword">while</span> (queue.waitForMessage())&#123;
       queue.processNextMessage();
    &#125;</code></pre>

<p>​        如果当前没有任何消息<code>queue.waitForMessage</code> 会等待同步消息到达,当完成当前任务后，继续去查看有无需要执行的任务如果需要执行，就再次执行，如此循环，所以称之为事件循环。</p>
<h4 id="同步和异步任务"><a href="#同步和异步任务" class="headerlink" title="同步和异步任务"></a>同步和异步任务</h4><p>​        要了解异步线程我们首先应该明白它的用处，因为js的<code>单线程</code>特性，任务的执行顺序都是依次执行，而当我们在工作中遇到网络请求，前后端交互的时候，你的数据不会马上拿到，这需要时间，如果等拿到数据再执行下面的代码，这样如果多次请求就会发现加载速度极慢，这样显然不合理，这样就会出现很多次的暂停等待，所以这时候 需要执行异步任务，当我们发起请求时候，采用异步的方式，浏览器检测到其为异步时，就会开辟一个新的进程处理该函数，然后继续执行后面的任务，当完成了执行栈里的同步任务之后，再检测是否有异步任务需要执行，最后执行异步任务。</p>
<pre><code class="hljs javascript">-同步任务进入主线程，按顺序从上而下依次执行，
-异步任务，进入<span class="hljs-string">`event table`</span> ，注册回调函数 <span class="hljs-string">`callback`</span> ，
 任务完成后，将<span class="hljs-string">`callback`</span>移入<span class="hljs-string">`event queue`</span>中等待主线程调用</code></pre>



<h4 id="异步任务分为微任务和宏任务"><a href="#异步任务分为微任务和宏任务" class="headerlink" title="异步任务分为微任务和宏任务"></a>异步任务分为微任务和宏任务</h4><p>​        在执行过程中，我们知道了同步任务会优先异步任务执行，那么在异步中呢，异步中同样包含微任务和宏任务，首先我们大概了解下微任务和宏任务，在js中：</p>
<ul>
<li>微任务(micor Task) ：promise  MutationObserver process.nextTick</li>
<li>宏任务(macro Task)：script settimeout setinterval setImmediate requestAnimationFrame</li>
</ul>
<blockquote>
<p>宏任务</p>
<table>
<thead>
<tr>
<th>#</th>
<th align="center">浏览器</th>
<th align="center">node</th>
</tr>
</thead>
<tbody><tr>
<td>I/O</td>
<td align="center">√</td>
<td align="center">√</td>
</tr>
<tr>
<td>setTimeOut</td>
<td align="center">√</td>
<td align="center">√</td>
</tr>
<tr>
<td>setInterval</td>
<td align="center">√</td>
<td align="center">√</td>
</tr>
<tr>
<td>setImmediate</td>
<td align="center">×</td>
<td align="center">√</td>
</tr>
<tr>
<td>requestAnimationFrame</td>
<td align="center">√</td>
<td align="center">×</td>
</tr>
</tbody></table>
<p>微任务</p>
<table>
<thead>
<tr>
<th>#</th>
<th align="center">浏览器</th>
<th align="center">node</th>
</tr>
</thead>
<tbody><tr>
<td>process.nextTick</td>
<td align="center">×</td>
<td align="center">√</td>
</tr>
<tr>
<td>MutationObserver</td>
<td align="center">√</td>
<td align="center">×</td>
</tr>
<tr>
<td>Promise.then catch finally</td>
<td align="center">√</td>
<td align="center">√</td>
</tr>
</tbody></table>
</blockquote>
<p>这两种任务在不同环境下支持的各不同，今天我们主要看看在浏览器中，我们经常会遇到的有 <code>promise</code> 和 <code>setTimeout</code> 我们通过下面这段代码来看看：</p>
<pre><code class="hljs javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">1</span>)

setTimeout(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-number">2</span>), <span class="hljs-number">0</span>)

<span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-number">3</span>)
    resolve()
&#125;).then(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-number">4</span>)
&#125;)</code></pre>

<p>首先来分析下，这段代码中包含同步任务，包含异步的宏任务<code>setTimeout</code>,包含异步的微任务<code>promise</code>,这套题的答案是1.3.4.2 ，我们首先找到同步任务，1 3 是同步任务，然后执行异步任务，异步任务如果按顺序执行则是24  但是答案是4.2那么我们可以知道 promise的执行顺序优先于setTimeout所以由此可知，在异步任务中，微任务优先于宏任务执行,可以看看下图。</p>
<p><img src="https://ae01.alicdn.com/kf/H587a24a44e6f4ac1bf6d9ec18b755b55D.jpg" srcset="/img/loading.gif" alt="eventloop"></p>
<p><code>红线就是任务的执行顺序</code></p>
<p><code>黑线是任务的结构</code></p>
<p>看完这么多下面来完成下面这道题并加以分析：</p>
<pre><code class="hljs javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-number">1</span>)
setTimeout(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-number">2</span>)
    <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> &#123;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-number">3</span>)
        resolve()
    &#125;).then(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> &#123;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-number">4</span>)
    &#125;)
&#125;, <span class="hljs-number">0</span>)
<span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-number">5</span>)
    resolve()
&#125;).then(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-number">6</span>)
&#125;)
setTimeout(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-number">7</span>)
    <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> &#123;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-number">8</span>)
        resolve()
    &#125;).then(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> &#123;
        <span class="hljs-built_in">console</span>.log(<span class="hljs-number">9</span>)
    &#125;)
&#125;, <span class="hljs-number">0</span>)
<span class="hljs-built_in">console</span>.log(<span class="hljs-number">10</span>)
<span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-number">1</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-number">2</span>);
  &#125;);
  promise.then(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> &#123;
    <span class="hljs-built_in">console</span>.log(<span class="hljs-number">3</span>);
  &#125;);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-number">4</span>);</code></pre>



<blockquote>
<p>答案：<code>1 , 5 , 10 , 6 , 2 , 3 , 4 , 7 , 8 , 9</code></p>
</blockquote>
<p>​    废话不多说直接解题</p>
<ul>
<li>进入主线程开始执行， 遇到 <code>console.log(1)</code>， 输出 <code>1</code></li>
<li>遇到一个 <code>setTimeout</code> 宏任务， 将其回调函数推入 <code>macro Task</code> 的 <code>event queue</code> 中，<code>macro Task</code> 的 <code>event queue</code> 中记一个任务 <code>setTimeout1</code></li>
<li>然后碰到 <code>promise</code> 微任务， 直接执行 <code>new Promise</code> 输出 <code>5</code>, 并将 <code>then</code> 函数的回调函数推入 <code>micro Task</code> 的 <code>event queue</code> 中, <code>micro Task</code> 的 <code>event queue</code> 中记 一个 微任务 <code>promise1</code></li>
<li>又遇到了 <code>setTimeout</code> 宏任务， 同理，将其回调函数推入 <code>macro Task</code> 的 <code>event queue</code> 中，<code>macro Task</code> 的 <code>event queue</code> 中记一个任务 <code>setTimeout2</code></li>
<li>最后，执行 <code>console.log(10)</code>, 输出 10</li>
</ul>
<blockquote>
<p>上一轮事件循环结束，我们发现，已经输出 <code>1 5 10</code> 了， 按照我们之前所说，这个时候，主线程会去检查 是否存在微任务，不难发现，这个时候的 <code>event queue</code> 是这个样子的</p>
</blockquote>
<table>
<thead>
<tr>
<th align="center"><strong>micro Task (微任务)</strong></th>
<th align="center"><strong>macro Task(宏任务)</strong></th>
</tr>
</thead>
<tbody><tr>
<td align="center">promise1</td>
<td align="center">setTimeout1</td>
</tr>
<tr>
<td align="center"></td>
<td align="center">setTimeout2</td>
</tr>
</tbody></table>
<pre><code class="hljs javascript">主线程 ---&gt; promis1 ---&gt; settimeout1 ---&gt; settimeou2 ---&gt; 循环检查主线程任务栈是否还有任务</code></pre>






            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/javascript/">javascript</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/js/">js</a>
                    
                      <a class="hover-with-bg" href="/tags/%E6%9C%BA%E5%88%B6/">机制</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/posts/7b91b8a9.html">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">栈内存与堆内存的区别</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/posts/7f8f311a.html">
                        <span class="hidden-mobile">神奇的grid布局</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script type="text/javascript">
    function loadValine() {
      addScript('https://cdn.staticfile.org/valine/1.4.14/Valine.min.js', function () {
        new Valine({
          el: "#vcomments",
          app_id: "3PpvuTN5QkO4Tih7TqE1W5u8-gzGzoHsz",
          app_key: "2URikzfu2z1jtCXMp3Sy6Oin",
          placeholder: "说点什么",
          path: window.location.pathname,
          avatar: "retro",
          meta: ["nick","mail","link"],
          pageSize: "10",
          lang: "zh-CN",
          highlight: false,
          recordIP: false,
          serverURLs: "",
        });
      });
    }
    createObserver(loadValine, 'vcomments');
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->



<!-- <script>
//去掉畅言下面的跳转连接
  //  声明定时器
var timer = null
//  检查dom是否执行完成
function checkDom() {
    let dom = document.querySelector('.service-wrap-w')
    if(dom) {
      console.log(dom)
         //  执行dom加载完成后的操作
         dom.innerHTML = ''
        //  清除定时器
        if(!timer) {
            clearTimeout(timer)
        }
    } else {
        //  自我调用
        timer = setTimeout(checkDom, 0)
    }
}
//  首次执行
checkDom()
</script> -->
      
    </main>

    
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
    

    
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    

    

    <footer class="mt-5">
  <div class="text-center py-3">
    <div>
      <!-- <a  rel="nofollow noopener"><span class="motto">故事若不曲折怎么教人成长</span></a> -->

      <!-- <a rel="nofollow noopener"><span class="motto">xiaojiu</span></a> -->
      <!-- <i class="iconfont icon-love"></i> -->
      <a rel="nofollow noopener">

        <!-- <span class="motto"> 可惜故事太长只有风听我讲</span></a> -->
        
        <span class="motto"> 黄粱一梦、山水万重、人间总相逢</span></a>
        <!-- <span class="motto"> blog</span></a> -->

    </div>
    


    

    
    <div class="xiaojiu">
      <span id="xiaojiu_container_site_pv" style="display: none;">本站已经被访问- <span id="xiaojiu_value_site_pv"
          style="margin: 0 3px;"> </span> -次啦</span>
      <span id="xiaojiu_container_site_uv" style="display: none;">已经有- <span id="xiaojiu_value_site_uv"
          style="margin: 0 3px;"> </span> -个小伙伴来过啦</span>
    </div>


    <div class="date">
      <span id="timeDate">载入天数...</span>
      <span class="times" id="times">载入时分秒...
      </span>
      <img class="time" src="/img/sml.gif" srcset="/img/loading.gif" alt="">
      <script>
        var now = new Date();
        function createtime() {
          var grt = new Date("05/08/2018 00:00:00");//此处修改你的建站时间或者网站上线时间
          now.setTime(now.getTime() + 250);
          days = (now - grt) / 1000 / 60 / 60 / 24;
          dnum = Math.floor(days);
          hours = (now - grt) / 1000 / 60 / 60 - (24 * dnum);
          hnum = Math.floor(hours);
          if (String(hnum).length == 1) {
            hnum = "0" + hnum;
          }
          minutes = (now - grt) / 1000 / 60 - (24 * 60 * dnum) - (60 * hnum);
          mnum = Math.floor(minutes);
          if (String(mnum).length == 1) {
            mnum = "0" + mnum;
          }
          seconds = (now - grt) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
          snum = Math.round(seconds);
          if (String(snum).length == 1) {
            snum = "0" + snum;
          }
          document.getElementById("timeDate").innerHTML = "本站已运行&nbsp" + dnum + "&nbsp天";
          document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";
        }
        setInterval("createtime()", 250);
      </script>
    </div>
</footer>
<!-- <script src="https://api.lzwzw.cn/public/js/xiaojiu.js"></script> -->
<!-- <script src="/js/xiaojiu.js"></script> -->
<script src="/js/message.js"></script>

<style>
  .xiaojiu {
    margin-top: 14px !important;
    background-image: linear-gradient(135deg, deeppink, dodgerblue);
    font-weight: bold;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    background-clip: text;
    box-decoration-break: clone;
    -webkit-box-decoration-break: clone;
    -moz-box-decoration-break: clone;
    color: transparent;
    position: relative;
  }

  .date {
    background-image: linear-gradient(135deg, deeppink, dodgerblue);
    font-weight: bold;
    -webkit-background-clip: text;
    -moz-background-clip: text;
    background-clip: text;
    box-decoration-break: clone;
    -webkit-box-decoration-break: clone;
    -moz-box-decoration-break: clone;
    color: transparent;
    position: relative;
  }
</style>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>







  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 6,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "event loop事件循环机制&nbsp;",
      ],
      cursorChar: "✨",
      typeSpeed: 80,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
      icon: "❡"
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  



  <script>(function (i, s, o, g, r, a, m) {
      i['DaoVoiceObject'] = r;
      i[r] = i[r] ||
        function () {
          (i[r].q = i[r].q || []).push(arguments);
        };
      i[r].l = 1 * new Date();
      a = s.createElement(o);
      m = s.getElementsByTagName(o)[0];
      a.async = 1;
      a.src = g;
      a.charset = 'utf-8';
      m.parentNode.insertBefore(a, m);
    })(window, document, 'script', ('https:' === document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/2b2e276c.js", 'daovoice');
    daovoice('init', {
      app_id: "2b2e276c",
    });
    daovoice('update');
  </script>










  </div>
  
</body>

</html>
<script>

  // https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture
  // https://source.unsplash.com/random  速度慢  有图还不错
  //https://uploadbeta.com/api/pictures/random/?key=%E6%8E%A8%E5%A5%B3%E9%83%8E 随机女图
  // https://api.jlongyan.cn/api/paper/random
  function checkWallaper() {
    fetch('https://source.unsplash.com/random', {
      method: 'GET',
      mode: 'cors',
    })
      .then(res => {
        setWallaper(res.url)
        localStorage.setItem('blogWallaper',res.url)
        return res.json()
      })
      // .then(res => {
      //   console.log(res);
      //   console.log("%c随机背景图片接口开放%c，随机壁纸api详情见博客,%c小九---!", "color:red", "", "color:orange;font-weight:bold")
      //   setWallaper(res.data.CoverImg)
      //   localStorage.setItem('blogWallaper',res.data.CoverImg)
      // })
      .catch(console.error)
  }

  if(localStorage.getItem('blogWallaper')){
    setWallaper(localStorage.getItem('blogWallaper'))
  }else{
    checkWallaper()
  }

  //设置壁纸
  function setWallaper(url){
    document.getElementById('indexBackground').style.backgroundImage = "url(" + url + ")";
  }

  let timer = null
  //  检查dom是否存在当前页面  监听 
  function watchYiyan() {
    let dom = document.getElementById('yiyan')
    if (dom) {
      fetch('https://v1.hitokoto.cn')
        .then(response => response.json())
        .then(data => {
          dom.innerText = data.hitokoto
        })
        .catch(console.error)
      if (!timer) {
        clearTimeout(timer)
      }
    } else {
      timer = setTimeout(watchYiyan, 0)
    }
  }
  //  首次执行
  watchYiyan()

  setTimeout(() => {
    clearTimeout(timer)
  }, 200);


</script>
